#!/usr/bin/env python 

import logging
"""
A capsulation of logging module

Usage:
    log = Log(fileBaseName,logName)
    log.err("some thing")
    log.info("some thing")
    log.debug("some thing")

Description:
    in "log = Log(fileBaseName,logName)" fileBaseName is the log filename whitch will concatenate to 
    be "fileBaseName.log" for logging level large than logging.INFO,and "fileBaseName.err" for logging level
    level large than logging.ERROR. logName is use by logging.getLogger()

    log.err logging things on level logging.ERROR
    log.info logging things on level logging.INFO
    log.debug loging things on level loging.DEBUG

    loging level on logging DEBUG will output to stdout while open it with Log.openDebug
"""

class ErrorFilter(logging.Filter):
    """
    This filte the log level higher than error to *.log file
    """
    def filter(self,record):
        if record.levelno >= logging.ERROR:
            return False
        else:
            return True
    

class Log(object):
    def __init__(self,fileBaseName,logName):
        self.fileBaseName = fileBaseName
        self.logName = logName
        _fmt = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        logFilePath = fileBaseName +".log"
        errFilePath = fileBaseName + ".err"

        self.logger = logging.getLogger(self.logName)
        self.logger.setLevel(logging.DEBUG)

        self.debugHdl = logging.StreamHandler()
        self.logHdl = logging.FileHandler(logFilePath)
        self.errHdl = logging.FileHandler(errFilePath)

        self.logHdl.setLevel(logging.INFO)
        self.errHdl.setLevel(logging.ERROR)
        self.debugHdl.setLevel(logging.DEBUG)  ## initiation with Debug open

        self.logHdl.setFormatter(logging.Formatter(_fmt))
        self.errHdl.setFormatter(logging.Formatter(_fmt))

        logHdlFilter = ErrorFilter()
        self.logHdl.addFilter(logHdlFilter)
        self.debugHdl.addFilter(logHdlFilter)

        self.logger.addHandler(self.debugHdl)
        self.logger.addHandler(self.logHdl)
        self.logger.addHandler(self.errHdl)

    def init(self,fileBaseName ,logName):
        self.fileBaseName = fileBaseName
        self.logName = logName

    def err(self,str,*args):
        self.logger.error(str,*args)

    def info(self,str,*args):
        self.logger.info(str,*args)

    def debug(self,str,*args):
        self.logger.debug(str,*args)

    def openDebug(self):        
        self.debugHdl.setLevel(logging.DEBUG)

    def closeDebug(self):
        self.debugHdl.setLevel(logging.CRITICAL)
                    



if "__main__" == __name__:
    log = Log("./log","LOG")
    log.openDebug()
    log.err("nimei!%s","nimei")
    log.info("nimei!%s","nimei")
    log.debug("nimei!%s","nimei")
